<?php

namespace App\Model;

use Illuminate\Http\Request;

class PearlRecord extends BaseModel
{
    protected $connection = 'mysql';
    protected $table = 'pearl_record';
    private $fields = ['id','user_id','change_pearl','created_at','type','desc','img','uuid','nickname','sys_notice'];
    protected $fillable = ['user_id','change_pearl', 'type','desc','img','uuid','nickname','sys_notice'];
    
    CONST TYPE_DEDUCT = 1;
    CONST TYPE_GIVE = 2;
    
    public function number(){
        return $this->belongsTo(Number::class,'user_id','user_id');
    }
    
    public function getList(Request $request){
        $limit = $request->input('limit',10);
        $page = $request->input('page',1);
        $type = $request->input('type','');  //默认扣款记录
        $uuid = $request->input('uuid','');
        $nickname = $request->input('nickname','');
        $begin = $request->input('begin','');
        $end = $request->input('end','');
        $query = new PearlRecord();
        // todo 搜索
        if($uuid) $query = $query->where('uuid',$uuid);
        if($nickname) $query = $query->where('nickname','like', "%{$nickname}%");
        if($begin && !$end) $query = $query->where('created_at','>=', $begin);
        if(!$begin && $end) $query = $query->where('created_at','<=', $end);
        if($begin && $end) $query = $query->whereBetween('created_at',[$begin,$end]);
        if($type) $query = $query->where('type', $type);
        return $query->orderBy('id','desc')->paginate($limit,$this->fields,'page',$page);
    }
    
    public function createData(Request $request,$changeDiamond, $nickname){
        return PearlRecord::create(array_merge($request->all(),['change_pearl' => $changeDiamond,'nickname' => $nickname]));
    }
    
    public function updateData(Request $request, $id){
        return PearlRecord::where('id',$id)->update($request->except('_url'));
    }
}
